package com.liuyi.netty.mqtt.processed.store.impl;

import com.liuyi.netty.mqtt.common.MqttConst;
import com.liuyi.netty.mqtt.processed.store.MqttSession;
import com.liuyi.netty.mqtt.processed.store.MqttSessionStore;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 内存级储存，只适用于单机模式
 *
 * @author Mr.Fmy
 * @since 2021-09-17
 */
public class MemoryMqttSessionStore implements MqttSessionStore {

    private final Map<String, MqttSession> mqttSessionMap = new HashMap<>(10000);


    @Override
    public MqttSession getByClientId(String clientId) {
        return mqttSessionMap.get(clientId);
    }

    @Override
    public void createSession(String clientId) {
        MqttSession session = new MqttSession();
        session.setClientId(clientId);
        session.setState(MqttConst.SessionState.ONLINE);
        session.setClusterStoreHost(MqttConst.SINGLE_MARKING);
        mqttSessionMap.put(clientId, session);
    }

    @Override
    public void clearSession(String clientId) {
        mqttSessionMap.remove(clientId);
    }

    @Override
    public void refreshSession(String clientId) {
        if (mqttSessionMap.containsKey(clientId)) {
            mqttSessionMap.get(clientId).setState(MqttConst.SessionState.ONLINE);
        }
    }


    @Override
    public void notSession(String clientId) {
        if (mqttSessionMap.containsKey(clientId)) {
            mqttSessionMap.get(clientId).setState(MqttConst.SessionState.NOT);
        }
    }

    @Override
    public void offlineSession(String clientId) {
        if (mqttSessionMap.containsKey(clientId)) {
            MqttSession session = mqttSessionMap.get(clientId);
            session.setState(MqttConst.SessionState.OFFLINE);
            session.setOfflineTime(LocalDateTime.now());
        }
    }

    @Override
    public int count() {
        return mqttSessionMap.size();
    }

    @Override
    public Collection<String> allClientIds() {
        return mqttSessionMap.keySet();
    }

}
